package com.play.ballen.utils;

import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;

public class GifUtil {

    public static void setDrawable(ImageView imageView, int normalId, int selectedId) {


        GIfStateListDrawable listDrawable = new GIfStateListDrawable();
        addState(imageView, new int[]{android.R.attr.state_selected}, selectedId, listDrawable, () -> {
            addState(imageView, new int[]{}, normalId, listDrawable, () -> {
                imageView.setImageDrawable(listDrawable);
            });
        });
    }

    private interface CallBack {
        void call();
    }

    private static void addState(ImageView imageView, int[] states, int resId, StateListDrawable listDrawable, CallBack callBack) {
        Glide.with(imageView)
                .asDrawable()
                .load(resId)
                .into(new CustomTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        listDrawable.addState(states, resource);
                        callBack.call();
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }


    public static class GIfStateListDrawable extends StateListDrawable {

        private  boolean stateChange=false;
        @Override
        protected boolean onStateChange(int[] stateSet) {
            boolean change=super.onStateChange(stateSet);
            if(change){
                stateChange=true;
            }
            return change;
        }

        @Override
        public void draw(Canvas canvas) {
            super.draw(canvas);
            if(stateChange) {
                //确保只播放一次gif
                stateChange=false;
                Drawable current = getCurrent();
                if (current instanceof GifDrawable) {
                    GifDrawable gifDrawable = (GifDrawable) current;
                    gifDrawable.setLoopCount(1);
                    gifDrawable.stop();
                    gifDrawable.startFromFirstFrame();
                }
            }
        }
    }

}
